using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using Microsoft.Practices.CompositeUI.Utility;
using System.Collections.ObjectModel;

namespace Jbe.TestSuite.LogViewer
{
    public static class LogRecorder
    {
        public static event EventHandler<DataEventArgs<LogEntry>> LogEntryAdded;
        public static event EventHandler LogCleared;

        private static IList<LogEntry> logEntries;
        private static ReadOnlyCollection<LogEntry> readOnlyLogEntries;
        private static bool enabled;

        public static ReadOnlyCollection<LogEntry> LogEntries
        {
            get { return readOnlyLogEntries; }
        }

        public static bool Enabled
        {
            get { return enabled; }
            set { enabled = value; }
        }

        static LogRecorder()
        {
            logEntries = new List<LogEntry>();
            readOnlyLogEntries = new ReadOnlyCollection<LogEntry>(logEntries);
            enabled = true;
        }

        public static void Log(LogEntry logEntry)
        {
            if (Enabled)
            {
                logEntries.Add(logEntry);
                OnLogEntryAdded(logEntry);
            }
        }

        public static void Log(object data)
        {
            if (Enabled)
            {
                LogEntry logEntry = new LogEntry();
                logEntry.Message = data.ToString();

                logEntries.Add(logEntry);
                OnLogEntryAdded(logEntry);
            }
        }

        public static void Clear()
        {
            logEntries.Clear();
            OnLogCleared();
        }

        private static void OnLogEntryAdded(LogEntry logEntry)
        {
            if (LogEntryAdded != null)
            {
                LogEntryAdded(typeof(LogRecorder), new DataEventArgs<LogEntry>(logEntry));
            }
        }

        private static void OnLogCleared()
        {
            if (LogCleared != null)
            {
                LogCleared(typeof(LogRecorder), new EventArgs());
            }
        }
    }
}
